//
//  YZPigDeathDetailVC.m
//  VET
//
//  Created by YZ on 2018/7/19.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZPigDeathDetailVC.h"
#import "YZPigDeathDetailViewModel.h"
#import "YZPigDeathDetailCell.h"
#import "YZPigDeathDetailRecordCell.h"
#import "TZImagePickerController.h"
#import "YZPigDocVC.h"
#import "YZBaseRefreshTableView.h"
#import "YYPhotoGroupView.h"

@interface YZPigDeathDetailVC ()<UITableViewDelegate,UITableViewDataSource,YZPigDeathDetailRecordCellDelegate>

@property (nonatomic, strong) YZPigDeathDetailViewModel *viewModel;

@property (nonatomic, strong) YZBaseRefreshTableView *contentTb;

@property (nonatomic, strong) UIView *pigDocView;

@property (nonatomic, strong) UILabel * pigDocLb;

@property (nonatomic, strong) UIImageView *imgView;

@end

@implementation YZPigDeathDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configUI];
    [self makeContraints];
    [self addObserver];
    [self.contentTb headerBeginRefresh];
}

- (void)configUI
{
    self.title = @"猪只死淘详情";
    [self.pigDocView addSubview:self.pigDocLb];
    [self.pigDocView addSubview:self.imgView];
    [self.view addSubview:self.contentTb];
    [self.view addSubview:self.pigDocView];
    
    YZWeakSelf(self);
    self.contentTb.headerRefreshBlock = ^{
        [weakself.contentTb resetState];
        [weakself.viewModel headerRefreshSuccess:^(id obj) {
            NSLog(@"obj:%ld",((NSArray *)obj).count);
            [weakself.contentTb reloadData];
            [weakself.contentTb headerEndRefresh];
        } fail:^(NSError *error) {
            [weakself.contentTb headerEndRefresh];
        }];
    };
    
    self.contentTb.footerRefreshBlock = ^{
        [weakself.viewModel footerRefreshSuccess:^(NSArray *obj) {
            if (obj.count == 0 && [weakself.viewModel isNoMoreData]) {
                [weakself.contentTb showNoMoreData];
                return;
            }
            [weakself.contentTb reloadData];
            [weakself.contentTb footerEndRefresh];
        } fail:^(NSError *error) {
            [weakself.contentTb footerEndRefresh];
        }];
    };
}

- (void)makeContraints
{
    [self.pigDocView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(kCurrentDeviceNum(54));
    }];
    
    [self.pigDocLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.pigDocView);
        make.width.mas_lessThanOrEqualTo(150);
    }];
    
    [self.imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.pigDocView);
        make.right.equalTo(self.pigDocLb.mas_left).offset(-kCurrentDeviceNum(5));
        make.size.mas_equalTo(CGSizeMake(kCurrentDeviceNum(24), kCurrentDeviceNum(24)));
    }];
    
    [self.contentTb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.equalTo(self.pigDocLb.mas_top);
    }];
}

- (void)addObserver
{
    [RACObserve(self.viewModel, loading) subscribeNext:^(id  _Nullable x) {
        if ([x boolValue]) {
            [SVProgressHUD show];
        }else
        {
            [SVProgressHUD dismiss];
        }
    }];
}

- (void)toPigDoc
{
    YZPigDocVC *pigDocVC = [YZPigDocVC new];
    YZPigModel *model = [YZPigModel new];
    model.pigId = self.model.objectId.integerValue;
    model.swineSex = self.model.dieoutSex;
    model.swineState = self.model.dieoutState;
    model.swineClass = self.model.dieoutClass;
    model.earMark = self.model.dieOutNO;
    model.swineBirthdate = self.model.birthdate;
    pigDocVC.model = model;
    [self.navigationController pushViewController:pigDocVC animated:YES];
}

#pragma mark -- YZPigDeathDetailRecordCellDelegate

- (void)deathDetailRecordImgDidSelectetdAtCell:(id)cell sourceUrls:(NSArray<YZPigDeathDetailRecordAttachmentModel *> *)urls sourceView:(YZPigDeathDetailRecordVideoCell *)view
{
//    NSMutableArray * photoModels = [NSMutableArray arrayWithCapacity:imgs.count];
//    for (int i =0 ; i < imgs.count; i++) {
//        TZAssetModel *model = [[TZAssetModel alloc] init];
//        model.cachedImage = imgs[i];
//        [photoModels addObject:model];
//    }
//    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:nil selectedPhotos:imgs photoModels:photoModels index:index];
//    imagePickerVc.maxImagesCount = 9;
//    imagePickerVc.allowPickingGif = NO;
//    imagePickerVc.allowPickingOriginalPhoto = NO;
//    imagePickerVc.allowPickingMultipleVideo = NO;
//    imagePickerVc.showSelectedIndex = YES;
//    imagePickerVc.isSelectOriginalPhoto = NO;
//    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    YZPigDeathDetailRecordCell *recordCell = (YZPigDeathDetailRecordCell *)cell;
    NSMutableArray *items = [NSMutableArray new];
    for (NSUInteger i = 0; i < urls.count; i++) {
        YZPigDeathDetailRecordAttachmentModel *url = urls[i];
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        item.largeImageURL = [NSURL URLWithString:url.attachmentUrl];
        item.thumbView = ((YZPigDeathDetailRecordVideoCell *)[recordCell.imgColloectView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]).imgView;
        [items addObject:item];
    }
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:view.imgView toContainer:self.navigationController.view animated:YES completion:nil];
}

- (void)deathDetailRecordVideoDidSelectedUrl:(NSString *)url sourceUrls:(NSArray<YZPigDeathDetailRecordAttachmentModel *> *)urls sourceView:(YZPigDeathDetailRecordVideoCell *)view
{
    NSMutableArray *items = [NSMutableArray new];
    for (NSUInteger i = 0; i < urls.count; i++) {
        YZPigDeathDetailRecordAttachmentModel *url = urls[i];
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        item.videoUrl = [NSURL URLWithString:url.attachmentUrl];
        item.largeImageURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?x-oss-process=video/snapshot,t_1000,w_400,h_0,m_fast,f_jpg",url.attachmentUrl]];
        item.thumbView = view.imgView;
        [items addObject:item];
    }
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:view.imgView toContainer:self.navigationController.view animated:YES completion:nil];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.viewModel.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.viewModel.dataSource[section].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if(indexPath.section == 0)
    {
        static NSString *cellId = @"YZPigDeathDetailCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if(!cell){
            cell = [[YZPigDeathDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        ((YZPigDeathDetailCell *)cell).model = [self.viewModel modelInSection:indexPath.section row:indexPath.row];
    }else
    {
        static NSString *cellId = @"YZPigDeathDetailRecordCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if(!cell){
            cell = [[YZPigDeathDetailRecordCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        ((YZPigDeathDetailRecordCell *)cell).delegate = self;
        ((YZPigDeathDetailRecordCell *)cell).model = [self.viewModel modelInSection:indexPath.section row:indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1)
    {
        return UITableViewAutomaticDimension;
    }
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1 && [self.viewModel modelsInSection:1].count != 0) {
        UIView *bgView = [[UIView alloc] init];
        bgView.backgroundColor = kColorWithHex(0xE9EAEB);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kCurrentDeviceNum(10), kScreenWidth, kCurrentDeviceNum(40))];
        view.backgroundColor = kColorWithHex(0xFFFFFF);
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(kCurrentDeviceNum(10), kCurrentDeviceNum(10), kCurrentDeviceNum(20), kCurrentDeviceNum(20))];
        imgView.image = [UIImage imageNamed:@"ico_tag"];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kCurrentDeviceNum(30), kCurrentDeviceNum(10), tableView.contentSize.width, kCurrentDeviceNum(20))];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.font = kCurrentDeviceBoldFont(16);
        titleLabel.text = @"死淘跟踪记录";
        titleLabel.textColor = kColorWithHex(0x434343);
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(kCurrentDeviceNum(20), kCurrentDeviceNum(39), kScreenWidth, kCurrentDeviceNum(1))];
        lineView.backgroundColor = kColorWithHex(0xE9EAEB);
        [view addSubview:imgView];
        [view addSubview:titleLabel];
        [view addSubview:lineView];
        [bgView addSubview:view];
        return bgView;
    }
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1 && [self.viewModel modelsInSection:1].count != 0) {
        return 50.f;
    }
    return 0.01;
}

#pragma mark -- setters && getters

- (YZBaseRefreshTableView *)contentTb
{
    if(!_contentTb){
        _contentTb = [[YZBaseRefreshTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _contentTb.tableFooterView = [UIView new];
        _contentTb.delegate = self;
        _contentTb.dataSource = self;
        _contentTb.estimatedRowHeight = 30;
        _contentTb.estimatedSectionHeaderHeight = 0;
        _contentTb.estimatedSectionFooterHeight = 0;
    }
    return _contentTb;
}

- (YZPigDeathDetailViewModel *)viewModel
{
    if(!_viewModel){
        _viewModel = [YZPigDeathDetailViewModel new];
        _viewModel.model = self.model;
    }
    return _viewModel;
}

- (UIView *)pigDocView
{
    if (!_pigDocView) {
        _pigDocView = [UIView new];
        _pigDocView.userInteractionEnabled = YES;
        _pigDocView.backgroundColor = kColorWithHex(0x32BE60);
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toPigDoc)];
        [_pigDocView addGestureRecognizer:tap];
    }
    return _pigDocView;
}

- (UILabel *)pigDocLb
{
    if (!_pigDocLb) {
        _pigDocLb = [[UILabel alloc] init];
        _pigDocLb.text = @"查看猪群档案";
        _pigDocLb.textColor = kColorWithHex(0xFFFFFF);
        _pigDocLb.font = kCurrentDeviceFont(16);
    }
    return _pigDocLb;
}

- (UIImageView *)imgView
{
    if (!_imgView) {
        _imgView = [UIImageView new];
        _imgView.image = [UIImage imageNamed:@"ico_piginfo_view"];
    }
    return _imgView;
}
@end
